const fs = require("fs");
const path = require("path");
const { exec } = require("child_process");
const { src, dest } = require("gulp");
const uglify = require("gulp-uglify");
const jsonmin = require("gulp-jsonmin");

const rootPath = path.resolve("./src");

const filePath = path.resolve("./dist/tsc");

// tsc 转译之后 gulp 打包压缩js
function jsToDist(dir, dirout) {
	src(`${dir}/*.js`)
		.pipe(uglify())
		.pipe(dest(`${dirout}/`));
}

// 处理项目中的 json 文件
function jsonToDist(dir, dirout) {
	src([`${dir}/*.json`])
		.pipe(jsonmin())
		.pipe(dest(`${dirout}/`));
}

// 处理项目中的 json 文件
function fileToDist(dir, dirout) {
	src([`${dir}/*`]).pipe(dest(`${dirout}/`));
}

//文件遍历方法
function fileDisplay(filePath, dir, dirout, callback, info = false) {
	callback(dir, dirout);
	let files = fs.readdirSync(filePath);
	files.forEach((filename) => {
		const nextdir = `${dir}\\${filename}`;
		const filedir = path.join(filePath, filename);
		let stats = fs.statSync(filedir);
		const isDir = stats.isDirectory();
		const isFile = stats.isFile();
		if (isFile && nextdir.startsWith('src') && info) {
			console.log(`Build File: ${dir}\\${filename}`);
		}
		if (isDir) {
			const nextdirout = `${dirout}\\${filename}`;
			fileDisplay(filedir, nextdir, nextdirout, callback, info);
		}
	});
}

// 执行 tsc 编译 tsc-alias 处理路径别名
const tscbuild = exec("tsc -p tsconfig.json && tsc-alias");

const binPath = path.resolve("./src/bin");
const publicPath = path.resolve("./src/public");

tscbuild.on("close", (code) => {
	fileDisplay(filePath, "dist\\tsc", "dist", jsToDist);
	fileDisplay(rootPath, "src", "dist", jsonToDist);
	fileDisplay(publicPath, "src\\public", "dist\\public", fileToDist);
	fileDisplay(binPath, "src\\bin", "dist\\bin", fileToDist);
	fileDisplay(rootPath, "src", "dist", jsToDist, true);
});

// 传递package.json
src(`package.json`).pipe(dest(`dist/`));
